<template>
  <div v-loading="butloading" class="AddExtensionPre">
    <div class="cus-title">
      <h4 v-if="state ==='edit'">编辑推广员</h4>
      <h4 v-else>添加推广员</h4>
    </div>
    <div class="cus-hearder">
      填写推广员信息
    </div>
    <div class="sub-form">
      <el-form ref="validate" label-position="right" label-width="100px" :model="BindForm" :rules="pattern">
        <el-form-item label="姓名:" prop="name">
          <el-col>
            <el-input
              v-model="BindForm.name"
              class="cus-input"
              maxlength="30"
              placeholder="输入名称"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="手机号码:" prop="phone">
          <el-col>
            <el-input
              v-model="BindForm.phone"
              class="cus-input"
              maxlength="11"
              placeholder="手机号码"
            />
          </el-col>
        </el-form-item>
        <el-form-item prop="address" label="城市:">
          <el-col>
            <city-select ref="citySelect" v-model="BindForm.address" style="margin-left: 0" @change="changeAddress" />
          </el-col>
        </el-form-item>
        <el-form-item label="推广方案:" prop="programme">
          <el-col>
            <el-select
              v-model="BindForm.programme"
              class="cus-input"
              style="width: 100%"
              clearable
              filterable
              placeholder="请选择推广方案"
            >
              <el-option
                v-for="(item, index) in BindataFA"
                :key="index"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="代理:" prop="proxy">
          <el-col>
            <ExtensionProxySelect v-model="BindForm.proxy" />
          </el-col>
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-col>
            <el-input
              v-model="BindForm.remark"
              type="textarea"
              placeholder="可填写备注内容"
              maxlength="100"
              show-word-limit
              class="cus-input"
              :rows="3"
              resize="none"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="">
          <el-col>
            <el-upload
              :action="uploadPath"
              list-type="picture-card"
              accept=".jpg, .png"
              :data="{path:path,fileType: 4}"
              :before-upload="beforeUpload"
              :on-success="uploadSuccess"
              :limit="limitCount"
              :on-change="isOverLimit"
              :on-remove="isRemoveImage"
              :file-list="images"
              :class="{hide:hideUpload}"
            >
              <i class="el-icon-plus" />
            </el-upload>
            <p class="ele-introduce">
              请上传jpg或png格式图片，大小不超过5M，最多上传{{ limitCount }}张
            </p>
          </el-col>
        </el-form-item>
        <el-form-item class="sub-footer">
          <el-button
            type="primary"
            :loading="butloading"
            @click="handelSubmit"
          >提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
/** 添加推广人员 */
import {
  ExtensionManagementAdd,
  schemeList,
  InventoryManagementEdit, getPromoterInfo
} from '@/api/customAPI/shop/ExtensionManagement'
import validate from '@/utils/formValidate'
import CitySelect from '../../../components/CitySelect/index'
import ExtensionProxySelect from '../../../components/ExtensionProxySelect/index'
import { uploadPath } from '@/api/upload'
export default {
  name: 'AddExtensionPre',
  components: { ExtensionProxySelect, CitySelect },
  data() {
    var validateCity = (rule, value, callback) => {
      if (!this.BindForm.address.province) {
        callback(new Error('请选择省份'))
      } else if (!this.BindForm.address.city) {
        callback(new Error('请选择市份'))
      } else if (!this.BindForm.address.village) {
        callback(new Error('请选择区县'))
      } else {
        callback()
      }
    }
    return {
      uploadPath,
      path: '/image',
      butloading: false,
      state: '',
      images: [],
      agentId: null,
      BindForm: {
        shopId: localStorage.getItem('shopId'),
        name: null,
        phone: null,
        programme: null,
        proxy: null,
        remark: null,
        address: {
          province: null,
          city: null,
          village: null
        }
      },
      BindataFA: [],
      hideUpload: false,
      limitCount: 9,
      pattern: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        address: [{ required: true, validator: validateCity, trigger: ['blur'] }],
        phone: [
          {
            required: true,
            min: 11,
            message: '请输入11位手机号',
            trigger: 'blur'
          },
          {
            validator: validate.validatePhone,
            trigger: ['change', 'blur']
          }
        ],
        programme: [
          {
            required: true,
            message: '请选择推广方案',
            trigger: ['change', 'blur']
          }
        ]
      }
    }
  },
  mounted() {
    this.Info()
  },
  methods: {
    changeAddress(data) {
      this.$refs.validate.validate((valid) => {

      })
    },
    isOverLimit(file, fileList) {
      this.hideUpload = fileList.length >= this.limitCount
    },
    isRemoveImage(file, fileList) {
      this.hideUpload = fileList.length >= this.limitCount
      const index = this.$XEUtils.findIndexOf(this.images, item => item.uid === file.uid)
      if (index >= 0) {
        this.images.splice(index, 1)
      }
    },
    beforeUpload(file) {
      let isJPG = false
      if ((file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg')) {
        isJPG = true
      }
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG、PNG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt5M
    },
    uploadSuccess(response, file) {
      file.imgUrl = response.data.relativePath
      this.images.push(file)
    },
    Info() {
      const params = this.$dd(this.$route.query.p)
      this.butloading = true

      if (params.state === 'add') {
        this.state = 'add'
        schemeList({
          shopId: localStorage.getItem('shopId'),
          keySearch: '',
          page: 1,
          limit: 0
        })
          .then(result => {
            this.BindataFA = result.data.data.data
            this.butloading = false
          })
          .catch(err => {
            console.log(err)
            this.butloading = false
          })
      } else if (params.state === 'edit') {
        this.state = params.state
        schemeList({
          shopId: localStorage.getItem('shopId'),
          keySearch: '',
          page: 1,
          limit: 0
        })
          .then(result => {
            console.log(result.data.data)
            console.log(params.row)
            this.BindataFA = result.data.data.data
            getPromoterInfo({ promoterId: params.row.agentId }).then(res => {
              this.BindForm.programme = res.data.data.customTemplateId
            })
            this.agentId = params.row.agentId
            /* this.BindForm.programme = params.row.customId*/
            this.BindForm.name = params.row.nickname
            this.BindForm.phone = params.row.mobile
            if (params.row.proxy) {
              this.BindForm.proxy = parseInt(params.row.proxy)
            }
            if (params.row.remark) {
              this.BindForm.remark = params.row.remark
            }
            if (params.row.province && params.row.city && params.row.village) {
              this.$refs.citySelect.setAddress(params.row.province, params.row.city, params.row.village)
            }
            if (params.row.images && params.row.images.length > 0) {
              params.row.images.split(',').forEach((image, index) => {
                this.images.push({
                  name: 'image' + index,
                  url: this.$parseImgUrl(image),
                  imgUrl: image
                })
              })
            }

            this.butloading = false
          })
          .catch(err => {
            console.log(err)
            this.butloading = false
          })
      } else {
        this.$router.push({ name: 'ExtensionManagement' })
        this.butloading = false
      }
    },
    handelSubmit() {
      const vm = this
      vm.butloading = true
      vm.$refs.validate.validate(v => {
        if (v) {
          if (vm.state === 'add') {
            const data = vm.$XEUtils.clone(vm.BindForm, true)
            data.shopId = localStorage.getItem('shopId')

            if (!data.proxy) {
              delete data.proxy
            }

            if (!data.remark) {
              delete data.remark
            }

            if (data.address && data.address.province && data.address.city && data.address.village) {
              data['provinceCode'] = data.address.province.code
              data['cityCode'] = data.address.city.code
              data['villageCode'] = data.address.village.code
            }
            delete data.address

            if (vm.images && vm.images.length > 0) {
              data['images'] = vm.$XEUtils.pluck(vm.images, 'imgUrl')
            } else {
              data['images'] = []
            }

            ExtensionManagementAdd(data)
              .then(result => {
                this.butloading = false
                this.$message.success('添加推广员成功')
                this.$store.dispatch('tagsView/delView', this.$route)
                this.$router.go(-1)
              }).catch(err => {
                console.log(err)
                this.butloading = false
              })
          } else if (this.state === 'edit') {
            const data = vm.$XEUtils.clone(vm.BindForm, true)
            data.shopId = localStorage.getItem('shopId')

            if (!data.proxy) {
              delete data.proxy
            }

            if (!data.remark) {
              delete data.remark
            }

            if (this.agentId) {
              data['agentId'] = this.agentId
            }
            if (data.address && data.address.province && data.address.city && data.address.village) {
              data['provinceCode'] = data.address.province.code
              data['cityCode'] = data.address.city.code
              data['villageCode'] = data.address.village.code
            }
            delete data.address

            if (vm.images && vm.images.length > 0) {
              data['images'] = vm.$XEUtils.pluck(vm.images, 'imgUrl')
            } else {
              data['images'] = []
            }

            InventoryManagementEdit(data)
              .then(result => {
                this.$message.success('编辑推广员成功')
                this.butloading = false
                this.$store.dispatch('tagsView/delView', this.$route)
                this.$router.go(-1)
              }).catch(err => {
                console.log(err)
                this.butloading = false
              })
          }
        } else {
          this.butloading = false
        }
      })
    }
  }
  /* beforeRouteEnter(to, from, next) {
    if (to.params.state === 'edit') {
      to.meta.title = '编辑推广员'
    } else {
      to.meta.title = '添加推广员'
    }
    next()
  },
  beforeRouteLeave(to, from, next) {
    // ....
    this.$store.dispatch('tagsView/delView', from)
    next()
  }*/
}
</script>
<style lang="scss" scoped>
.ele-introduce {
  font-size: 14px;
  color: gray;
}
.AddExtensionPre {
  padding: 50px 100px;
  .cus-hearder {
    font-size: 0.9rem;
    height: 50px;
    border-radius: 5px;
    line-height: 50px;
    padding: 0px 20px;
    background: #f3f3f3;
  }
  .sub-form {
    margin-top: 30px;

    .cus-input {
      max-width: 400px;
    }

    ::v-deep .hide .el-upload--picture-card {
      display: none !important;
    }

    ::v-deep .el-upload-list__item {
      width: 100px;
      height: 100px;
    }

    ::v-deep .el-upload--picture-card {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }

  }
}
</style>
